<?php

namespace App\Console\Commands\Guanyuan;

use App\Exceptions\Custom\ResponseHttpException;
use App\Library\FeiShu\SendFs;
use App\Models\Clickhouse\Guanyuan\GyDailyDeliveryReportCHModel;
use App\Models\Guanyuan\GuanyuanSyncShopBusinessModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;

class ShopList extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'guanyuan:shopList';

    /**
     * The console command description.
     * 每天同步观远数据到tiger数据库中  减少观远查询
     * @var string
     */
    protected $description = '观远门店列表同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');

        Log::info('GUANYUAN-' . '开始同步观远门店数据');

        //获取观远门店列表数据
        GuanyuanDataService::setTimeOut(30);
        $shopList       = GuanyuanDataService::newShopList();
        $totalShopCount = count($shopList);

        if ($totalShopCount == 0) {
            return;
        }

        // 补充ShopId
        $shopIds = [];
        $shopLastActivity = [];
        ShopModel::query()
            ->select(['id', 'shopCode'])
            ->chunkById(500, function ($shops) use (&$shopIds,&$shopLastActivity) {
                $shopCodes = [];
                foreach ($shops as $shop) {
                    $shopIds[$shop->shopCode] = $shop->id;
                    $shopCodes[$shop->shopCode] = $shop->shopCode;
                }
                try {
                    $shopLastActivity = array_merge(
                        $shopLastActivity,
                        GyDailyDeliveryReportCHModel::getLastActivityDateByShopCode($shopCodes)
                    );
                } catch (\Exception $exception){
                    Log::info($exception);
                    BuildFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
                           ->setTitleContent("同步观远数据clickhouse获取异常", $exception->getMessage())
                           ->setAtUid('ag6g472g')
                           ->send();
                }
            });
        $shopLastActivity = array_column($shopLastActivity,null,'storeCode');

        // 需要添加的数据
        $insertData         = [];
        $insertDataBusiness = [];
        //同步到数据库
        $counter = 0;
        collect($shopList)->chunk(50)->each(function ($shops) use (&$counter, $totalShopCount, &$insertData, &$insertDataBusiness, $shopIds,$shopLastActivity) {
            $counter += 50;
            $this->info('当前进度：' . round($counter / $totalShopCount, 4) * 100 . '%');
            // 获得观远的门店数据

            // 每个门店最近的收入汇总
            $actualIncomeShopList = [];

            // 每个门店最近营业额评级
            $shopGradeList = [];

            Log::info('GUANYUAN-' . '当前进度：' . round($counter / $totalShopCount, 4) * 100 . '%');
            collect($shops)->chunk(10)->each(function ($business) use (&$actualIncomeShopList, &$shopGradeList, &$insertDataBusiness) {
                $shopCodes = collect($business)->map(function ($shopInfo) {
                    return str_pad($shopInfo['铺位号'], 4, '0', STR_PAD_LEFT);
                })->toArray();
                Log::info('GUANYUAN-' . '获得营业额数据');
                GuanyuanDataService::setTimeOut(35);
                $guanyuanDataList = GuanyuanDataService::getShopBusinessInfoByCode(array_values($shopCodes), 30, 1);
                foreach ($guanyuanDataList as $guanyuanData) {

                    if (!isset($actualIncomeShopList[(int)($guanyuanData['门店编码'] ?? 0)])) {
                        $actualIncomeShopList[(int)($guanyuanData['门店编码'] ?? 0)] = ((float)($guanyuanData['订单实收金额'] ?? 0));
                    } else {
                        $actualIncomeShopList[(int)($guanyuanData['门店编码'] ?? 0)] += ((float)($guanyuanData['订单实收金额'] ?? 0));
                    }

                    // 获得昨天的门店等级
                    if ($guanyuanData['日期'] == Carbon::now()->subDay()->format('Y-m-d')) {
                        $shopGradeList[(int)($guanyuanData['门店编码'] ?? 0)] = $guanyuanData['门店分级'] ?? '';
                    }

//                    if (!isset($shopGradeList[(int)($guanyuanData['门店编码'] ?? 0)])) {
//                        $shopGradeList[(int)($guanyuanData['门店编码'] ?? 0)] = $guanyuanData['门店分级'] ?? '';
//                    } else {
//                        if ($lastDate <= strtotime($guanyuanData['日期'] ?? '')) {
//                            $shopGradeList[(int)($guanyuanData['门店编码'] ?? 0)] = $guanyuanData['门店分级'] ?? '';
//                            $lastDate                                             = strtotime($guanyuanData['日期'] ?? '');  //变更最新的时间
//                        }
//                    }

                    $insertDataBusiness[] = [
                        'placementType'                  => (string)($guanyuanData['投放类型'] ?? ''),
                        'placementStartDate'             => (string)($guanyuanData['投放开始时间'] ?? ''),
                        'businessType'                   => (string)($guanyuanData['门店类型'] ?? ''),
                        'name'                           => (string)($guanyuanData['门店名称'] ?? ''),
                        'code'                           => (int)($guanyuanData['门店编码'] ?? 0),
                        'region'                         => (string)($guanyuanData['区域'] ?? ''),
                        'date'                           => (string)($guanyuanData['日期'] ?? ''),
                        'orderNum'                       => (int)($guanyuanData['订单量'] ?? 0),
                        'isMonthNew'                     => (int)($guanyuanData['是否本月新开'] ?? 0),
                        'dailyArtificial'                => (float)($guanyuanData['日人工'] ?? 0),
                        'dailyEnergy'                    => (float)($guanyuanData['日能源'] ?? 0),
                        'roi'                            => (float)($guanyuanData['roi'] ?? 0),
                        'estimatedProfit'                => (float)($guanyuanData['预估利润'] ?? 0),
                        'openingDurationMonth'           => (float)($guanyuanData['开业时长（月）'] ?? 0),
                        'openingDurationDay'             => (float)($guanyuanData['开业时长（天）'] ?? 0),
                        'area'                           => (float)($guanyuanData['门店面积'] ?? 0),
                        'orderTurnover'                  => (float)($guanyuanData['订单营业额'] ?? 0),
                        'orderDiscountAmount'            => (float)($guanyuanData['订单优惠金额'] ?? 0),
                        'orderReceivedAmount'            => (float)($guanyuanData['订单实收金额'] ?? 0),
                        'employeesNum'                   => (int)($guanyuanData['员工人数'] ?? 0),
                        'province'                       => (string)($guanyuanData['省份'] ?? ''),
                        'city'                           => (string)($guanyuanData['城市'] ?? ''),
                        'takeawayTurnover'               => (float)($guanyuanData['外卖订单营业额'] ?? 0),
                        'takeawayDiscountAmount'         => (float)($guanyuanData['外卖订单优惠金额'] ?? 0),
                        'takeawayReceivedAmount'         => (float)($guanyuanData['外卖订单实收金额'] ?? 0),
                        'dineInTurnover'                 => (float)($guanyuanData['堂食订单营业额'] ?? 0),
                        'dineInDiscountAmount'           => (float)($guanyuanData['堂食订单优惠金额'] ?? 0),
                        'dineInReceivedAmount'           => (float)($guanyuanData['堂食订单实收金额'] ?? 0),
                        'dineInEstimatedProfit'          => (float)($guanyuanData['堂食预估利润'] ?? 0),
                        'takeawayEstimatedProfit'        => (float)($guanyuanData['外卖预估利润'] ?? 0),
                        'takeawayOrderNum'               => (int)($guanyuanData['外卖订单量'] ?? 0),
                        'dineInOrderNum'                 => (int)($guanyuanData['堂食订单量'] ?? 0),
                        'openBusinessDate'               => (string)($guanyuanData['开业日期'] ?? ''),
                        'closeDate'                      => (string)($guanyuanData['闭店时间'] ?? ''),
                        'franchiseeName'                 => (string)($guanyuanData['加盟商'] ?? ''),
                        'dailyRent'                      => (float)($guanyuanData['日房租'] ?? 0),
                        'rent'                           => (float)($guanyuanData['房租'] ?? 0),
                        'district'                       => (string)($guanyuanData['区县'] ?? ''),
                        'storeActiveStatus'              => (string)($guanyuanData['门店活跃状态'] ?? ''),
                        'status'                         => (string)($guanyuanData['状态'] ?? ''),
                        'artificial'                     => (float)($guanyuanData['人工'] ?? 0),
                        'breakEvenPoint'                 => (float)($guanyuanData['保本点'] ?? 0),
                        'monthlyBusinessDays'            => (int)($guanyuanData['月营业天数'] ?? 0),
                        'dailyReceivedAmount'            => (float)($guanyuanData['日均实收'] ?? 0),
                        'monthlyDays'                    => (int)($guanyuanData['实际月天数'] ?? 0),
                        'isCloseShop'                    => (int)($guanyuanData['是否本年闭店'] ?? 0),
                        'address'                        => (string)($guanyuanData['店铺地址'] ?? ''),
                        'cityGrade'                      => (string)($guanyuanData['城市等级'] ?? ''),
                        'reArea'                         => (float)($guanyuanData['面积'] ?? 0),
                        'roiType'                        => (string)($guanyuanData['ROI分类'] ?? ''),
                        'vipCardTurnover'                => (float)($guanyuanData['会员卡订单营业额'] ?? 0),
                        'vipCardDiscountAmount'          => (float)($guanyuanData['会员卡订单优惠金额'] ?? 0),
                        'vipCardReceivedAmount'          => (float)($guanyuanData['会员卡订单实收金额'] ?? 0),
                        'vipCardOrderNum'                => (int)($guanyuanData['会员卡订单量'] ?? 0),
                        'franchiseeRealName'             => (string)($guanyuanData['加盟商真名'] ?? ''),
                        'dailyRentCost'                  => (float)($guanyuanData['日房租成本'] ?? 0),
                        'elmTurnover'                    => (float)($guanyuanData['饿了么订单营业额'] ?? 0),
                        'elmDiscountAmount'              => (float)($guanyuanData['饿了么订单优惠金额'] ?? 0),
                        'elmReceivedAmount'              => (float)($guanyuanData['饿了么订单实收金额'] ?? 0),
                        'elmOrderNum'                    => (int)($guanyuanData['饿了么订单量'] ?? 0),
                        'mtTurnover'                     => (float)($guanyuanData['美团订单营业额'] ?? 0),
                        'mtDiscountAmount'               => (float)($guanyuanData['美团订单优惠金额'] ?? 0),
                        'mtReceivedAmount'               => (float)($guanyuanData['美团订单实收金额'] ?? 0),
                        'mtOrderNum'                     => (int)($guanyuanData['美团订单量'] ?? 0),
                        'operationManager'               => (string)($guanyuanData['运营负责人'] ?? ''),
                        'privateDomain'                  => (string)($guanyuanData['私域'] ?? ''),
                        'operationalStatus'              => (string)($guanyuanData['代运营状态'] ?? ''),
                        'averageDailyProfit'             => (float)($guanyuanData['日均利润'] ?? 0),
                        'receiptGrading'                 => (int)($guanyuanData['实收分级'] ?? 0),
                        'ProfitClassification'           => (int)($guanyuanData['利润分级'] ?? 0),
                        'weightRoi'                      => (int)($guanyuanData['加权ROI'] ?? 0),
                        'whetherLoss'                    => (string)($guanyuanData['是否亏损'] ?? ''),
                        'shopGrade'                      => (string)($guanyuanData['门店分级'] ?? ''),
                        'siteLocationType'               => (string)($guanyuanData['选址分类'] ?? ''),
                        'elmRating'                      => (float)($guanyuanData['饿了么评分'] ?? 0),
                        'mtRating'                       => (float)($guanyuanData['美团评分'] ?? 0),
                        'mtStoreId'                      => (string)($guanyuanData['美团门店ID_改'] ?? ''),
                        'elmStoreId'                     => (string)($guanyuanData['饿了么门店ID_改'] ?? ''),
                        'cashierSystem'                  => (string)($guanyuanData['收银系统'] ?? ''),
                        'elmStar1'                       => (int)($guanyuanData['1星评价数-e'] ?? 0),
                        'elmStar2'                       => (int)($guanyuanData['2星评价数-e'] ?? 0),
                        'elmStar3'                       => (int)($guanyuanData['3星评价数-e'] ?? 0),
                        'elmStar4'                       => (int)($guanyuanData['4星评价数-e'] ?? 0),
                        'elmStar5'                       => (int)($guanyuanData['5星评价数-e'] ?? 0),
                        'mtStar1'                        => (int)($guanyuanData['1星评价数-m'] ?? 0),
                        'mtStar2'                        => (int)($guanyuanData['2星评价数-m'] ?? 0),
                        'mtStar3'                        => (int)($guanyuanData['3星评价数-m'] ?? 0),
                        'mtStar4'                        => (int)($guanyuanData['4星评价数-m'] ?? 0),
                        'mtStar5'                        => (int)($guanyuanData['5星评价数-m'] ?? 0),
                        'elmWaimaiShopId'                => (string)($guanyuanData['waimaiShopId-饿'] ?? ''),
                        'elmWaimaiShopName'              => (string)($guanyuanData['waimaiShopName-饿'] ?? ''),
                        'mtWaimaiShopId'                 => (string)($guanyuanData['waimaiShopId-美'] ?? ''),
                        'mtWaimaiShopName'               => (string)($guanyuanData['waimaiShopName-美'] ?? ''),
                        'takeawayStartTime'              => (string)($guanyuanData['外卖介入时间'] ?? ''),
                        'takeawayOldOrNew'               => (string)($guanyuanData['外卖新店判断'] ?? ''),
                        'performanceRanges'              => (string)($guanyuanData['业绩区间'] ?? ''),
                        'activityType'                   => (string)($guanyuanData['活动类型'] ?? ''),
                        'storeType'                      => (string)($guanyuanData['铺位类型'] ?? ''),
                        'takeawayBusinessDays'           => (int)($guanyuanData['外卖营业天数'] ?? 0),
                        'temperatureMax'                 => (string)($guanyuanData['temperatureMax'] ?? ''),
                        'temperatureMin'                 => (string)($guanyuanData['temperatureMin'] ?? ''),
                        'recentAttention'                => (string)($guanyuanData['近期关注'] ?? ''),
                        'nightWeather'                   => (string)($guanyuanData['晚上天气'] ?? ''),
                        'noonWeather'                    => (string)($guanyuanData['中午天气'] ?? ''),
                        'developmentManager'             => (string)($guanyuanData['开发经理'] ?? ''),
                        'operationSupervision'           => (string)($guanyuanData['运营督导'] ?? ''),
                        'keyCity'                        => (string)($guanyuanData['重点城市'] ?? ''),
                        'relocationMark'                 => (string)($guanyuanData['迁址标记'] ?? ''),
                        'elmRepurchaseRate'              => (float)($guanyuanData['饿了么复购率'] ?? 0),
                        'elmBusinessCirclePeerMean'      => (float)($guanyuanData['饿了么商圈同行均值'] ?? 0),
                        'elmBusinessCirclePeerMeanTop10' => (float)($guanyuanData['饿了么商圈同行TOP10均值'] ?? 0),
                        'mtRepurchaseRate'               => (float)($guanyuanData['美团复购率'] ?? 0),
                        'mtBusinessCirclePeerMean'       => (float)($guanyuanData['美团商圈同行均值'] ?? 0),
                        'mtBusinessCirclePeerMeanTop10'  => (float)($guanyuanData['美团商圈同行TOP10均值'] ?? 0),
                        'secondaryLeader'                => (string)($guanyuanData['二级负责人'] ?? ''),
                        'mallGrade'                      => (string)($guanyuanData['商场分级'] ?? ''),
                        'createdAt'                      => time(),
                        'updatedAt'                      => time(),
                    ];
                }
                //GuanyuanSyncShopBusinessModel::query()->insert($insertDataBusiness);
            });
            foreach ($shops as $shop) {
                $shopCode       = (int)($shop['铺位号'] ?? 0);
                $lastActivityAt = (string)($shopLastActivity[$shopCode]['date'] ?? '');

                $insertData[] = [
                    'region'                  => (string)($shop['区域'] ?? ''),
                    'operationManager'        => (string)($shop['运营负责人'] ?? ''),
                    'privateDomain'           => (string)($shop['私域'] ?? ''),
                    'takeawayStartTime'       => (string)($shop['外卖介入时间'] ?? ''),
                    'code'                    => $shopCode,
                    'shopId'                  => $shopIds[(int)($shop['铺位号'] ?? 0)] ?? 0,
                    'name'                    => (string)($shop['门店名称'] ?? ''),
                    'status'                  => (string)($shop['状态'] ?? ''),
                    'businessType'            => (string)($shop['经营类型'] ?? ''),
                    'storeType'               => (string)($shop['铺位类型'] ?? ''),
                    'cashierSystem'           => (string)($shop['收银系统'] ?? ''),
                    'province'                => (string)($shop['门店所在省'] ?? ''),
                    'city'                    => (string)($shop['门店所在市'] ?? ''),
                    'district'                => (string)($shop['区/县'] ?? ''),
                    'belongBranch'            => (string)($shop['所属分公司'] ?? ''),
                    'address'                 => (string)($shop['店铺地址'] ?? ''),
                    'contractStartDate'       => (string)($shop['合同开始日期'] ?? ''),
                    'contractEndDate'         => (string)($shop['合同结束日期'] ?? ''),
                    'openBusinessDate'        => (string)($shop['开业日期'] ?? ''),
                    'closeDate'               => (string)($shop['闭店时间'] ?? ''),
                    'franchiseFee'            => (float)($shop['加盟费'] ?? 0),
                    'managementFee'           => (float)($shop['管理费'] ?? 0),
                    'transferFee'             => (float)($shop['技术转让费'] ?? 0),
                    'area'                    => (float)($shop['面积'] ?? 0),
                    'rent'                    => (float)($shop['房租'] ?? 0),
                    'artificial'              => (float)($shop['人工'] ?? 0),
                    'energy'                  => (float)($shop['能源'] ?? 0),
                    'employeesNum'            => (int)($shop['员工人数'] ?? 0),
                    'operationSupervision'    => (string)($shop['运营督导'] ?? ''),
                    'developmentManager'      => (string)($shop['开发经理'] ?? ''),
                    'siteLocationType'        => (string)($shop['选址分类'] ?? ''),
                    'inputPrice'              => (float)($shop['一次性投入-新'] ?? 0),
                    'phone'                   => (string)($shop['电话'] ?? ''),
                    'degreeOfCooperation'     => (string)($shop['配合程度'] ?? ''),
                    'franchiseeRealName'      => (string)($shop['加盟商真名'] ?? ''),
                    'franchiseeName'          => (string)($shop['加盟商'] ?? ''),
                    'franchiseConsultant'     => (string)($shop['加盟顾问'] ?? ''),
                    'preparatoryConsultant'   => (string)($shop['筹备顾问'] ?? ''),
                    'preparatoryFinishDate'   => (string)($shop['筹备完成日期'] ?? ''),
                    'preparatoryStartDate'    => (string)($shop['筹备开始日期'] ?? ''),
                    'preparatoryTimeConsumed' => (int)($shop['筹备耗时'] ?? 0),
                    'openShopTimeConsumed'    => (int)($shop['开店耗时'] ?? 0),
                    'lng'                     => (float)($shop['门店经度'] ?? 0),
                    'lat'                     => (float)($shop['门店纬度'] ?? 0),
                    'designConsultant'        => (string)($shop['设计顾问'] ?? ''),
                    'designStartDate'         => (string)($shop['设计开始日期'] ?? ''),
                    'designEndDate'           => (string)($shop['设计结束日期'] ?? ''),
                    'currentStatus'           => (string)($shop['当前状态'] ?? ''),
                    'currentNodeName'         => (string)($shop['当前节点名称'] ?? ''),
                    'estimatedOpeningTime'    => (string)($shop['预计开业时间'] ?? ''),
                    'relocationMark'          => (string)($shop['迁址标记'] ?? ''),
                    'keyCity'                 => (string)($shop['重点城市'] ?? ''),
                    'subStatus'               => (string)($shop['子状态'] ?? ''),
                    'earliestRevenueDate'     => (string)($shop['最早有营收日期'] ?? ''),
                    'orderNo'                 => (string)($shop['订单编号'] ?? ''),
                    'confirmSiteDate'         => (string)($shop['确址日期'] ?? ''),
                    'shopGrade'               => $shopGradeList[(int)($shop['铺位号'] ?? 0)] ?? '',
                    'actualIncome'            => round($actualIncomeShopList[(int)($shop['铺位号'] ?? 0)] ?? 0, 2),
                    'createdAt'               => time(),
                    'updatedAt'               => time(),
                    'lastActivityAt'          => $lastActivityAt ? strtotime($lastActivityAt) : 0,
                ];
            }
            // 添加入库
            //GuanyuanSyncShopListModel::query()->insert($insertData);
        });

        $insertDataCount = count($insertData);
        $insertDataChunk = array_chunk($insertData, 100);

        Log::info('GUANYUAN-' . '门店列表总数' . $insertDataCount);

        if ($insertDataCount > 2900) {
            //截断表
            GuanyuanSyncShopListModel::query()->truncate();

            // 添加入库
            foreach ($insertDataChunk as $insertDataChunkSelf) {
                GuanyuanSyncShopListModel::query()->insert($insertDataChunkSelf);
            }
        }

        $insertDataBusinessCount = count($insertDataBusiness);

        Log::info('GUANYUAN-' . '门店经营列表总数' . $insertDataBusinessCount);

        if ($insertDataBusinessCount) {
            //截断表
            GuanyuanSyncShopBusinessModel::query()->truncate();
            $insertDataBusinessChunk = array_chunk($insertDataBusiness, 100);
            // 添加入库
            foreach ($insertDataBusinessChunk as $insertDataBusinessChunkSelf) {
                GuanyuanSyncShopBusinessModel::query()->insert($insertDataBusinessChunkSelf);
            }
        }

        $pageNum = 0;
        // 同步到RMS
        try {
            // 同步数据
            foreach ($insertDataChunk as $k => $item) {
                $pageNum = $k;
                RmsShopRemote::syncGuanYuanShopList($item);
            }
        } catch (\Exception $exception) {
            BuildFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
                ->setTitleContent("HTTP同步观远门店信息至RMS失败", '总数据量:' . $insertDataCount . "\n 在第{$pageNum}页")
                ->setAtUid('513296d9') //彼得潘
                ->send();
        }
    }
}
